package com.talkingdata.hadoop.guard.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class LoadUrl {
    public static String getString(String url ){
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json.toString();
    }
    public static String getOneMetric(String url ,String metric) throws IOException {
        String urlinfo = LoadUrl.getString(url);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode beans = objectMapper.readTree(urlinfo).path("beans");
        String value = beans.get(0).get(metric).asText();
        return value;
    }
    public static JsonNode getOneMetricOnYarn(String url ,String metric) throws IOException {
        String urlinfo = LoadUrl.getString(url);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(urlinfo).path(metric);
        return jsonNode;
    }
}
